<template>
  <view class="container">
    <!-- 拼团列表区域 -->
    <view class="group-list-section">
      <!-- 列表标题 -->
      <view class="section-header">
        <text class="section-title">热门拼团</text>
        <view class="sort-dropdown" @tap="showSortOptions = !showSortOptions">
          <text>{{ currentSortText }}</text>
          <text class="dropdown-icon">▼</text>
        </view>
      </view>

      <!-- 排序选项弹出层 -->
      <view class="sort-options" v-if="showSortOptions">
        <view 
          v-for="option in sortOptions" 
          :key="option.value"
          :class="['sort-option', currentSort === option.value ? 'active' : '']"
          @tap="setSortOption(option.value)"
        >
          {{ option.text }}
        </view>
      </view>

      <!-- 拼团列表 -->
      <scroll-view 
        scroll-y 
        class="group-list"
        @scrolltolower="loadMore"
      >
        <view 
          v-for="(item, index) in displayedItems" 
          :key="index"
          class="group-item"
          @tap="navigateToDetail(item.id)"
        >
          <!-- 左侧信息区 -->
          <view class="item-main">
            <view class="item-title-row">
              <text class="item-title">{{ item.title }}</text>
              <text class="flight-number">{{ item.flightNumber }}</text>
            </view>
            
            <view class="route-info">
              <text class="city">{{ item.departure }}</text>
              <text class="arrow">→</text>
              <text class="city">{{ item.destination }}</text>
              <text class="time">{{ item.departureTime }} - {{ item.arrivalTime }}</text>
            </view>

            <view class="date-info">
              <text class="date">{{ item.date }}</text>
              <text class="deadline">剩余{{ formatCountdown(item.deadline) }}</text>
            </view>
          </view>

          <!-- 右侧成员头像区 -->
          <view class="member-avatars">
            <view class="avatar-stack">
              <image 
                v-for="n in item.currentMembers" 
                :key="n"
                :style="{ zIndex: item.currentMembers - n }"
                src="https://picsum.photos/50/50?random=1" 
                class="member-avatar"
              />
              <view class="remaining-count" v-if="item.requiredMembers > item.currentMembers">
                +{{ item.requiredMembers - item.currentMembers }}
              </view>
            </view>
            <button class="join-btn" @tap.stop="joinGroup(item.id)">参与</button>
          </view>
        </view>

        <!-- 加载更多 -->
        <view class="load-more" v-if="!isAllLoaded">
          <view class="loading-indicator" v-if="isLoading">
            <view class="loading-spinner"></view>
            <text class="loading-text">加载中...</text>
          </view>
        </view>
        <view class="all-loaded" v-else>已经到底啦 ~</view>
      </scroll-view>
    </view>

    <!-- TabBar -->
    <cc-myTabbar :tabBarShow="0"></cc-myTabbar>
  </view>
</template>

<script>
import { qrcode, coach, edit_info, getUserInfo } from "../../api/fit";

export default {
  data() {
    return {
      currentSort: 'recommended',
      showSortOptions: false,
      sortOptions: [
        { text: '推荐排序', value: 'recommended' },
        { text: '即将截止', value: 'deadline' },
        { text: '价格最低', value: 'priceAsc' },
        { text: '成团最快', value: 'grouping' }
      ],
      isLoading: false,
      isAllLoaded: false,
      page: 1,
      displayedItems: [
        {
          id: 1,
          title: "首尔3日休闲游",
          image: "https://picsum.photos/id/10/800/600",
          date: "2024-04-15",
          departure: "上海",
          destination: "首尔",
          flightNumber: "KE925",
          departureTime: "09:30",
          arrivalTime: "12:45",
          currentMembers: 3,
          requiredMembers: 5,
          deadline: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(), // 24小时后
          groupPrice: 2999,
          originalPrice: 3999
        },
        {
          id: 2,
          title: "济州岛度假团",
          image: "https://picsum.photos/id/11/800/600",
          date: "2024-04-20",
          departure: "北京",
          destination: "济州岛",
          flightNumber: "OZ334",
          departureTime: "10:15",
          arrivalTime: "13:30",
          currentMembers: 4,
          requiredMembers: 6,
          deadline: new Date(Date.now() + 48 * 60 * 60 * 1000).toISOString(), // 48小时后
          groupPrice: 3499,
          originalPrice: 4599
        },
        {
          id: 3,
          title: "釜山美食之旅",
          image: "https://picsum.photos/id/12/800/600",
          date: "2024-04-25",
          departure: "广州",
          destination: "釜山",
          flightNumber: "KE688",
          departureTime: "08:45",
          arrivalTime: "11:50",
          currentMembers: 2,
          requiredMembers: 4,
          deadline: new Date(Date.now() + 36 * 60 * 60 * 1000).toISOString(), // 36小时后
          groupPrice: 2599,
          originalPrice: 3299
        }
      ]
    };
  },

  computed: {
    currentSortText() {
      const option = this.sortOptions.find(opt => opt.value === this.currentSort);
      return option ? option.text : '推荐排序';
    }
  },

  methods: {
    formatCountdown(deadline) {
      const now = new Date();
      const end = new Date(deadline);
      const diff = end - now;

      if (diff <= 0) return '已结束';

      const hours = Math.floor(diff / (1000 * 60 * 60));
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));

      return `${hours}小时${minutes}分钟`;
    },

    setSortOption(value) {
      this.currentSort = value;
      this.showSortOptions = false;
      
      // 根据排序选项对列表进行排序
      this.displayedItems.sort((a, b) => {
        switch (value) {
          case 'deadline':
            return new Date(a.deadline) - new Date(b.deadline);
          case 'priceAsc':
            return a.groupPrice - b.groupPrice;
          case 'grouping':
            return (b.currentMembers / b.requiredMembers) - (a.currentMembers / a.requiredMembers);
          default:
            return 0;
        }
      });
    },

    loadMore() {
      if (this.isLoading || this.isAllLoaded) return;
      
      this.isLoading = true;
      
      // 模拟加载更多数据
      setTimeout(() => {
        const newItems = this.generateMoreItems();
        if (newItems.length === 0) {
          this.isAllLoaded = true;
        } else {
          this.displayedItems = [...this.displayedItems, ...newItems];
          this.page++;
        }
        this.isLoading = false;
      }, 1000);
    },

    generateMoreItems() {
      // 模拟生成更多数据
      if (this.page >= 3) return []; // 模拟数据到底

      const cities = ['东京', '大阪', '札幌', '冲绳', '名古屋'];
      const newItems = [];

      for (let i = 0; i < 3; i++) {
        const id = this.displayedItems.length + i + 1;
        newItems.push({
          id,
          title: `${cities[Math.floor(Math.random() * cities.length)]}休闲游`,
          image: `https://picsum.photos/id/${12 + id}/800/600`,
          date: this.generateRandomDate(),
          departure: ['上海', '北京', '广州'][Math.floor(Math.random() * 3)],
          destination: cities[Math.floor(Math.random() * cities.length)],
          flightNumber: `NH${Math.floor(Math.random() * 1000)}`,
          departureTime: this.generateRandomTime(),
          arrivalTime: this.generateRandomTime(true),
          currentMembers: Math.floor(Math.random() * 3) + 1,
          requiredMembers: Math.floor(Math.random() * 3) + 4,
          deadline: new Date(Date.now() + (Math.random() * 72 + 24) * 60 * 60 * 1000).toISOString(),
          groupPrice: Math.floor(Math.random() * 2000) + 2000,
          originalPrice: Math.floor(Math.random() * 3000) + 3000
        });
      }

      return newItems;
    },

    generateRandomDate() {
      const date = new Date();
      date.setDate(date.getDate() + Math.floor(Math.random() * 30) + 1);
      return date.toISOString().split('T')[0];
    },

    generateRandomTime(isArrival = false) {
      const hours = isArrival ? 
        Math.floor(Math.random() * 6) + 12 : 
        Math.floor(Math.random() * 6) + 8;
      const minutes = Math.floor(Math.random() * 60);
      return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
    },

    joinGroup(id) {
      uni.navigateTo({
        url: `/pages/concert/detail?id=${id}&action=join`
      });
    },

    navigateToDetail(id) {
      uni.navigateTo({
        url: `/pages/concert/detail?id=${id}`
      });
    }
  }
};
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: linear-gradient(135deg, #8BC6EC 0%, #9599E2 100%);
  padding: 20rpx;
}

.group-list-section {
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border-radius: 20rpx;
  border: 1px solid rgba(255, 255, 255, 0.3);
  padding: 20rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 36rpx;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.9);
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.sort-dropdown {
  background: rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: rgba(255, 255, 255, 0.9);
  font-size: 28rpx;
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.sort-options {
  position: absolute;
  right: 20rpx;
  top: 120rpx;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border-radius: 20rpx;
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8rpx 32rpx rgba(31, 38, 135, 0.15);
  z-index: 100;
}

.sort-option {
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: rgba(0, 0, 0, 0.7);
  border-bottom: 1px solid rgba(255, 255, 255, 0.3);

  &.active {
    color: #007AFF;
    background: rgba(0, 122, 255, 0.1);
  }
}

.group-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 15rpx;
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: transform 0.3s ease;

  &:active {
    transform: scale(0.98);
  }
}

.item-main {
  flex: 1;
  margin-right: 20rpx;
}

.item-title-row {
  display: flex;
  align-items: center;
  gap: 10rpx;
  margin-bottom: 8rpx;
}

.item-title {
  font-size: 28rpx;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.9);
}

.flight-number {
  font-size: 22rpx;
  color: #007AFF;
  background: rgba(0, 122, 255, 0.2);
  padding: 2rpx 8rpx;
  border-radius: 8rpx;
}

.route-info {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-bottom: 6rpx;
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.9);
}

.arrow {
  color: rgba(255, 255, 255, 0.6);
  margin: 0 4rpx;
}

.time {
  margin-left: 10rpx;
  color: rgba(255, 255, 255, 0.7);
}

.date-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 22rpx;
}

.date {
  color: rgba(255, 255, 255, 0.7);
}

.deadline {
  color: #FF3B30;
}

.member-avatars {
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.avatar-stack {
  display: flex;
  align-items: center;
}

.member-avatar {
  width: 50rpx;
  height: 50rpx;
  border-radius: 25rpx;
  border: 2rpx solid rgba(255, 255, 255, 0.8);
  margin-left: -15rpx;
  
  &:first-child {
    margin-left: 0;
  }
}

.remaining-count {
  background: rgba(255, 255, 255, 0.3);
  width: 50rpx;
  height: 50rpx;
  border-radius: 25rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20rpx;
  color: rgba(255, 255, 255, 0.9);
  margin-left: -15rpx;
  border: 2rpx solid rgba(255, 255, 255, 0.8);
}

.join-btn {
  background: rgba(255, 149, 0, 0.3);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  border: 1px solid rgba(255, 149, 0, 0.3);
  border-radius: 25rpx;
  padding: 8rpx 20rpx;
  color: #FF9500;
  font-size: 24rpx;
  height: auto;
  line-height: 1.5;
  margin: 0;

  &:active {
    transform: scale(0.95);
  }
}

.load-more {
  text-align: center;
  padding: 20rpx;
}

.loading-indicator {
  display: inline-flex;
  align-items: center;
  gap: 10rpx;
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  padding: 10rpx 30rpx;
  border-radius: 30rpx;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.loading-spinner {
  width: 30rpx;
  height: 30rpx;
  border: 3rpx solid rgba(255, 255, 255, 0.3);
  border-top: 3rpx solid #FFFFFF;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  color: rgba(255, 255, 255, 0.9);
  font-size: 26rpx;
}

.all-loaded {
  text-align: center;
  color: rgba(255, 255, 255, 0.6);
  font-size: 26rpx;
  padding: 20rpx;
}
</style>
